<?php

namespace App\Http\Controllers\Admin;

use App\Http\Model\Admin\Goods;
use Illuminate\Http\Request;

use Illuminate\Support\Facades\DB;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Pagination\BootstrapThreePresenter;

class GoodsController extends Controller
{
    /**
     *          商品列表
     *
     * @return $this
     */
    public function goods_list()
    {

        $data = DB::table('goods')
                    ->leftjoin('img','goods.goods_id','=','img.goods_id')
                    ->leftjoin('tag','goods.tag_id','=','tag.tag_id')
                    ->leftjoin('classify','goods.c_id','=','classify.c_id')
                    ->select('goods.*','img.img_src','tag.tag_name','classify.c_name')
                    ->paginate(10);
        //print_r($data);
        return view('Admin/Goods/goods_li')->with('data',$data);

    }


    /**
     *          添加商品
     *
     * @param Request $request
     * @return $this
     */
    public function goods_add(Request $request)
    {
        if ($request->isMethod('get'))
        {
            $data['tag_list'] = DB::table('tag')->get();
            $data['class_list'] = DB::table('classify')->where('tag_id','=',$data['tag_list'][0]->tag_id)->get();
            $data['property_list'] = DB::table('property')->where('property.c_id',1)->get();
            $c_ids = [];
            foreach ($data['property_list']  as $v)
            {
                $c_ids[] = $v->p_id;
            }
            $data['property_value'] = DB::table('property_value')->whereIn('p_id',$c_ids)->get();
            //print_r($data);
            return view('Admin/Goods/add_goods')->with('data',$data);
        }

        if ($request->isMethod('post'))
        {
            $data = $request->input('data');

            $data = json_decode($data,true);
            $r = $this->check_goods_info($data);
            if ($r['status']  == 0)
            {
                return  response()->json($r);
            }
            if (empty($data['img_src']))
            {
                return response()->json(['info'=>'图片地址为空','status'=>0]);
            }
            DB::beginTransaction();
            $goods = new Goods();

//            $goods->traansacyion;
            $goods->goods_num       = $data['goods_num'];
            $goods->tag_id          = $data['tag_id'];
            $goods->c_id            = $data['classify'];
            $goods->p_id            = 0;
            $goods->goods_name      = $data['goods_name'];
            $goods->goods_describe      = $data['des'];
            $goods->stock           = $data['stock'];
            $goods->status          = 0;
            $goods->hot             = 0;
            $goods->price           = $data['price'];
            $res = $goods->save();

            if ($res)
            {
                // 获取返回id
                $goods_id = $goods->goods_id;
                // 添加图片地址
                $a = [];
                foreach ($data['img_src'] as $v)
                {
                    $tmp = [];
                    $tmp['img_src'] = $v;
                    $tmp['goods_id'] = $goods_id;
                    $tmp['status']    = 0 ;
                    $tmp['p_id']      = 0 ;
                    $a[] =$tmp;
                }

                $imgres = DB::table('img')->insert($a);

                // 添加属性
                $b = [];


                foreach ($data['property']  as $v)
                {
                    $p_v = explode('-',$v,2);
                    $tmp = [];
                    $tmp['goods_id'] = $goods_id;
                    $tmp['property_id'] = $p_v[0];
                    $tmp['property_value'] = $p_v[1];
                    //return response()->json(['status'=>$bbb]);
                    $b[] = $tmp;
                }

                $goods_res = DB::table('goods_property')->insert($b);

                if ($imgres  && $goods_res)
                {
                    DB::commit();
                    return response()->json(['info'=>'保存成功','status'=>1]);
                }else{
                    DB::rollback();
                    return response()->json(['info'=>'图片保存失败，请重试','status'=>0]);
                }
            }else{
                    DB::rollback();
                    return response()->json(['info'=>'保存失败，请重试','status'=>0]);
            }

        }
    }

    /**
     *          检验商品的信息
     *
     * @param $data
     * @return bool|\Illuminate\Http\JsonResponse
     */
    public function check_goods_info($data)
    {
        if (empty($data['classify']))
        {
            return ['info'=>'类别为空','status'=>0];
        }
        if (empty($data['des']))
        {
            return ['info'=>'产品描述为空','status'=>0];
        }
        if (empty($data['goods_name']))
        {
            return ['info'=>'产品描述为空','status'=>0];
        }
        if (empty($data['goods_num']))
        {
            return ['info'=>'产品编号为空','status'=>0];
        }

        if (empty($data['price']))
        {
            return ['info'=>'产品价格为空','status'=>0];
        }
        if (empty($data['stock']))
        {
            return ['info'=>'产品库存为空','status'=>0];
        }
        if (empty($data['tag_id']))
        {
            return ['info'=>'产品标签为空','status'=>0];
        }

        return ['info'=>'验证成功','status'=>1];
    }

    /**
     *          改变分类信息
     *
     * @param Request $request
     * @return array
     */
    public function change_class(Request $request)
    {
        $id   = $request->input('id');
        $type = $request->input('type');

        switch ($type)
        {
            case $type == 'tag':

                $data1['class_list']      = DB::table('classify')->where('tag_id',$id)->get();
                $data1['property_list'] = DB::table('property')->where('c_id',$data1['class_list'][0]->c_id)->get();
                $c_ids = [];
                foreach ($data1['property_list']  as $v)
                {
                    $c_ids[] = $v->p_id;
                }
                $property_value = DB::table('property_value')->whereIn('p_id',$c_ids)->get();
                $str = '';
                foreach ($data1['property_list'] as $v)
                {
                    $s = '';
                    foreach ($property_value  as $vv)
                    {
                        if ($v->p_id == $vv->p_id)
                        {
                            $s .= '<input type="checkbox" value="'.$v->p_id.'-'.$vv->p_value.'" name="like[write]" title="'.$vv->p_value.'">';
                        }
                    }

                    $str .= '<li class="panel panel-default"  ><div class="panel-header">'.$v->p_name.'</div><div class="panel-body"> <div >'.$s.' </div>  </div> </li>';
                }

                $data1['property_list'] = $str;
                return ['list'=>$data1];
                break;
            case $type == 'classify':
                $data = DB::table('property')->where('c_id',$id)->get();

                $c_ids = [];
                foreach ($data  as $v)
                {
                    $c_ids[] = $v->p_id;
                }

                $property_value = DB::table('property_value')->whereIn('p_id',$c_ids)->get();
                $str = '';
                foreach ($data as $v)
                {
                    $s = '';
                    foreach ($property_value  as $vv)
                    {
                        if ($v->p_id == $vv->p_id)
                        {
                            $s .= '<input type="checkbox" value="'.$v->p_id.'-'.$vv->p_value.'" name="like[write]" title="'.$vv->p_value.'">';
                        }
                    }

                    $str .= '<li class="panel panel-default"  ><div class="panel-header">'.$v->p_name.'</div><div class="panel-body"> <div >'.$s.' </div>  </div> </li>';
                }

                $data['property_list'] = $str;
                return $data;
                break;
            default :
                return ['info'=>'未知错误'];
        }
    }

    /**
     *          改变商品上下架状态
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function change_goods_status(Request $request)
    {
       if ($request->isMethod('post'))
       {
           $id = (int)$request->input('goods_id');
           $status = (int)$request->input('status');

           $res = DB::table('goods')->where('goods_id',$id)->get();



           if ($res)
           {
               if ($status === $res[0]->status)
               {
                   return response()->json(['info'=>'状态一样，不需要修改','status'=>0]);
               }
               if ($status  === 1)
               {
                   $upres = DB::table('goods')->where('goods_id',$id)->update(['status'=>1]);
                   if ($upres)
                   {
                       return response()->json(['info'=>'发布成功','status'=>1]);
                   }else{
                       return response()->json(['info'=>'发布失败','status'=>0]);
                   }

               }else{
                   $upres = DB::table('goods')->where('goods_id',$id)->update(['status'=>0]);
                   if ($upres)
                   {
                       return response()->json(['info'=>'下架成功','status'=>1]);
                   }else{
                       return response()->json(['info'=>'下架失败','status'=>0]);
                   }
               }
           }else{
               return response()->json(['info'=>'没有该商品，请确认后重试','status'=>0]);
           }


       }

    }

    /**
     *          上传文件
     *
     * @param Request $request
     * @return string
     */
    public function post_file_upload(Request $request){


        //判断请求中是否包含name=file的上传文件
        if(!$request->hasFile('file')){
            return '上传文件为空！';
        }

        $file = $request->file('file');

        //判断文件上传过程中是否出错
        if(!$file->isValid()){
            return ('文件上传出错！');
        }
        $newFileName = md5(time().rand(0,10000)).'.'.$file->getClientOriginalExtension();

        $file->move('img/goods/',$newFileName);

        $savePath = 'img/goods/'.$newFileName;
        if (file_exists($savePath))
        {
            $path = '/'.'img/goods/'.$newFileName;
            return ['info'=>'上传成功','savepath'=>$path];
        }else{
            return ['info'=>'上传失败'];
        }
//
    }


    /**
     *          修改商品信息
     *
     * @param Request $request
     * @param $id
     * @return $this|\Illuminate\Http\JsonResponse
     */
    public function goods_edit(Request $request,$id)
    {
        //

        if ($request->isMethod('get'))
        {

            $data['goods_info']      = DB::table('goods')->join('img',function ($join) use ($id) {
                                                             $join->on('goods.goods_id','=','img.goods_id')
                                                                  ->where('goods.goods_id','=',$id);
                                                         })
                                                         ->get();
            $data['tag_list']        = DB::table('tag')->get();
            $data['class_list']      = DB::table('classify')->where('tag_id',$data['goods_info'][0]->tag_id)->get();
            $data['property_list']   = DB::table('property')->where('c_id',$data['goods_info'][0]->c_id)->get();
            $c_ids = [];
            foreach ($data['property_list']  as $v)
            {
                $c_ids[] = $v->p_id;
            }
            $data['property_value'] = DB::table('property_value')->whereIn('p_id',$c_ids)->get();
            //print_r($data);
            return view('Admin/Goods/goods_edit')->with('data',$data);
        }

        if ($request->isMethod('post'))
        {
            $data = $request->input('data');

            $data = json_decode($data,true);
            $id = $data['id'];

            DB::beginTransaction();
            $good = new Goods();
            $goods = $good->find($id);
            if (!$goods)
            {
                return response()->json(['info'=>'找不到该商品','status'=>0]);
            }

            $r = $this->check_goods_info($data);
            if ( $r['status']  == 0)
            {
                return  response()->json($r);
            }

            $goods->goods_num       = $data['goods_num'];
            $goods->tag_id          = $data['tag_id'];
            $goods->c_id            = $data['classify'];
            $goods->p_id            = 0;
            $goods->goods_name      = $data['goods_name'];
            $goods->goods_describe      = $data['des'];
            $goods->stock           = $data['stock'];
            $goods->status          = 0;
            $goods->hot             = 0;
            $goods->price           = $data['price'];
            $res = $goods->save();

            if ($res  !== true)
            {
                return response()->json(['info'=>'修改失败，请重试','status'=>0]);
            }
            $goods_id = $id;
            if (!empty($data['img_src']))
            {

                //更换图片
                $a = [];
                foreach ($data['img_src'] as $v)
                {
                    $tmp = [];
                    $tmp['img_src'] = $v;
                    $tmp['goods_id'] = $goods_id;
                    $tmp['status']    = 0 ;
                    $tmp['p_id']      = 0 ;
                    $a[] =$tmp;
                }
                //todo 更换更多的图片
                $imgres = DB::table('img')->where('goods_id',$goods_id)->update($a[0]);

                // 添加属性
                $b = [];


                foreach ($data['property']  as $v)
                {
                    $p_v = explode('-',$v);
                    $tmp = [];
                    $tmp['goods_id'] = $goods_id;
                    $tmp['property_id'] = $p_v[0];
                    $tmp['property_value'] = $p_v[1];
                    //return response()->json(['status'=>$bbb]);
                    $b[] = $tmp;
                }

                $del = DB::table('goods_property')->where('goods_id',$goods_id)->delete();
                if ($del)
                {
                    $goods_res = DB::table('goods_property')->where('goods_id',$goods_id)->insert($b);
                }else{
                    DB::rollback();
                    return response()->json(['info'=>'属性保存失败1，请重试','status'=>0]);
                }


                if ($imgres && $goods_res)
                {
                    DB::commit();
                    return response()->json(['info'=>'保存成功','status'=>1]);
                }else{
                    DB::rollback();
                    return response()->json(['info'=>'图片保存失败，请重试','status'=>0]);
                }
            }else{

                // 添加属性
                $b = [];


                foreach ($data['property']  as $v)
                {
                    $p_v = explode('-',$v);
                    $tmp = [];
                    $tmp['goods_id'] = $goods_id;
                    $tmp['property_id'] = $p_v[0];
                    $tmp['property_value'] = $p_v[1];
                    //return response()->json(['status'=>$bbb]);
                    $b[] = $tmp;
                }

                $del = DB::table('goods_property')->where('goods_id',$goods_id)->delete();
                if ($del)
                {
                    $goods_res = DB::table('goods_property')->where('goods_id',$goods_id)->insert($b);
                    if ($goods_res)
                    {
                        DB::commit();
                        return response()->json(['info'=>'保存成功','status'=>1]);
                    }else{
                        DB::rollback();
                        return response()->json(['info'=>'属性保存失败2','status'=>0]);
                    }

                }else{
                    DB::rollback();
                    return response()->json(['info'=>'属性保存失败3，请重试','status'=>0]);
                }

            }

        }



    }


    /**
     *          商品删除
     *
     * @param Request $request
     * @param $id
     * @return array
     */
    public function goods_del(Request $request, $id)
    {
        //
        if ($request->isMethod('post'))
        {
            DB::beginTransaction();
            $res = DB::table('goods')->where('goods_id', '=', $id)->delete();
            $res1 = DB::table('img')->where('goods_id', '=', $id)->delete();
            $res2 = DB::table('')->where('goods_id', '=', $id)->delete();
            //todo 服务器图片的处理
            if ($res1  && $res && $res2)
            {
                DB::commit();
                return ['info'=>'删除成功','status'=>1];
            }else{
                DB::rollback();
                return ['info'=>'删除失败','status'=>0];
            }

        }
    }


    /**
     *          修改商品热销状态
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function change_hot_status(Request $request )
    {
        //
        if ($request->isMethod('post'))
        {
            $id = (int)$request->input('goods_id');
            $status   = (int)$request->input('status');

            $res = DB::table('goods')->where('goods_id',$id)->get();

            if ($res)
            {
                if ($status === $res[0]->hot)
                {
                    return response()->json(['info'=>'状态一样，不需要修改','status'=>0]);
                }
                if ($status  === 1)
                {
                    $upres = DB::table('goods')->where('goods_id',$id)->update(['hot'=>1]);
                    if ($upres)
                    {
                        return response()->json(['info'=>'修改成功1','status'=>1]);
                    }else{
                        return response()->json(['info'=>'修改失败1','status'=>0]);
                    }

                }else{
                    $upres = DB::table('goods')->where('goods_id',$id)->update(['hot'=>0]);
                    if ($upres)
                    {
                        return response()->json(['info'=>'修改成功2','status'=>1]);
                    }else{
                        return response()->json(['info'=>'修改失败2','status'=>0]);
                    }
                }
            }else{
                return response()->json(['info'=>'没有该商品，请确认后重试','status'=>0]);
            }
        }
    }
}


















